﻿interface ISailConfig {
    Root: string,
    ApiRoot: string,
    PageContent: string,
}
interface JQueryStatic {
    SailConfig: ISailConfig;

    setSailConfig(set: ISailConfig): void;

    templatesRoot: string;

    view(obj: any): any;

    growl(text: string, obj: any): JQuery;
    /**
     * 获取url参数
     * @param {type} name
     */
    Request(name: string): string;
    /**
     * 把url的参数序列化成对象
     */
    decodeParam(): Object;
    /**
     * 把对象编码成字符串
     * @param {Object} obj
     */
    encodeObject(obj: Object): string;
    /**
     * 把编码后的字符串还原成对象
     * @param {string} str
     */
    decodeObject(str: string): Object;

    /**
     * 双向绑定工具
     * @param container 待绑定的容器
     * @param {Object} objItem 要绑定的默认数据
     */
    ItemBinder(container: any, objItem: Object): Sail.Binder;

    /**
     * ajax delete方法
     * @param {type} url 地址
     * @param {type} data? 要提交的数据
     * @param {type} act? 成功后执行的方法
     */
    Delete(url: string, data?: any, act?: Function): JQueryXHR;
    /**
     *  ajax put方法
     * @param {type} url 地址
     * @param {type} data? 要提交的数据
     * @param {type} act? 成功后执行的方法
     */
    Put(url: string, data?: any, act?: Function): JQueryXHR;
    /**
     * 读取html文本
     * @param {string} tname
     */
    LoadHtml(tname: string): string;
    /**
     * 读取模板
     * @param {string} tname
     */
    Loadtmpl(tname: string): JsRender.Template;

    /**
     * 创建分页控件
     * @param {type} set
     */
    Pagination(set: Sail.IPaginationSetting): Sail.Pagination;

    /**
     * 读取后台序列化并转换成json的对象
     * @param {type} obj
     */
    LoadParam(obj: JQuery): JSON;
    /**
     * 创建弹窗
     * @param {string} id
     * @param {Sail.ModalSetting} set
     */
    CreateModal(id: string, set: Sail.IModalSetting): Sail.Modal;
};


function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

module Sail {
    export interface AjaxResult {
        IsSuccess: Boolean,
        Data: any,
        Msg: string;
    }

    $.setSailConfig = (set: ISailConfig) => {
        $.SailConfig = $.extend({
            Root: "/",
            ApiRoot: "/Api/",
            PageContent: ".flexbox-content"
        }, set);
    };

    $.setSailConfig(null);

    $.CreateModal = (id: string, set: IModalSetting): Modal => new Modal(id, set);

    //读取参数
    $.LoadParam = obj => JSON.parse(decodeURIComponent(btoa($(obj).val())));


    ///把url后面的参数序列化成对象
    $.decodeParam = () => {
        if (!location.search) return {};
        var search = location.search.substring(1);
        return JSON.parse(`{"${decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`);
    };

    //把对象编码成字符串
    $.encodeObject = (obj: Object) => atob(encodeURIComponent(JSON.stringify(obj)));

    //把编码后的字符串还原成对象
    $.decodeObject = (str: string) => JSON.parse(decodeURIComponent(btoa(str)));

    /**
     * 获取url参数
     * @param name
     * @returns
     */
    $.Request = name => {

        var url = window.location.href;
        var reg = new RegExp(`(\\?|&)${name}=([^&?#]*)`, 'i');
        var arr = url.match(reg);
        if (arr) return decodeURIComponent(arr[2]);
        return "";
    };
     

    /**
     * 双向绑定工具
     * @param container
     * @param {Object} objItem
     * @returns
     */
    $.ItemBinder = (container: any, objItem: Object): Binder => {
        var result = new Binder(container, objItem);
        return result;
    };


    $.Delete = (url: string, data?: any, act?: any): JQueryXHR => {
        if (typeof data == "function") {
            act = data;
            data = null;
        }
        return $.ajax({
            url: url,
            type: "delete",
            data: data,
            dataType: "json",
            success: act
        });

    };

    $.Put = (url: string, data?: any, act?: any): JQueryXHR => {
        if (typeof data == "function") {
            act = data;
            data = null;
        }
        return $.ajax({
            type: "put",
            url: url,
            data: data,
            dataType: "json",
            success: act
        });
    };



    ///加载html内容
    $.LoadHtml = (tmplName: string): string => {
        //获取真实模版文件名
        function formatTemplatePath(name: string): string {
            return $.SailConfig.Root + "templates/" + name + ".tmpl.html";
        };
        var tmplHtml = "";
        if (tmplName) {
            if (tmplName.indexOf("#") == 0) {
                var template = $(tmplName).loadRemoteTmpl().html();
                tmplHtml = template;
            }
            else {
                tmplHtml = $(document).data(tmplName + "_Tmpl");
                if (!tmplHtml)
                    $.ajax({
                        url: formatTemplatePath(tmplName),
                        async: false,
                        cache: false,
                        success: template => {
                            tmplHtml = template;
                            $(document).data(tmplName + "_Tmpl", template);
                        }
                    });
            }
        }
        return tmplHtml;
    };

    $.Loadtmpl = (tmplName: string): JsRender.Template => {//同步模式读取模板文件的方法
        var tmplHtml = $.LoadHtml(tmplName);
        return $.templates(tmplHtml);
    }

    $.Pagination = (set: IPaginationSetting): Pagination => new Pagination(set);
}